package com.project.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpRequestUtils {
    /**
     * @param urlPath
     * @param parameterMap
     * @return
     * 示例：
     *  Map dataMap = new HashMap();
        dataMap.put("username", "admin");
        dataMap.put("email", "IT@qq.com");
        String url="http://localhost:8089/test/findUser";
        String res= HttpRequestUtils.httpPost(url,dataMap);
        JSONObject jsonObject= JSONObject.fromObject(res);
     */
    public static String httpPost(String urlPath, Map parameterMap) {

         /* Translate parameter map to parameter date string */
        StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                if (parameterMap.get(key) != null) {
                    value = (String) parameterMap.get(key);
                } else {
                    value = "";
                }

                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }

        //System.out.println("POST parameter : " + parameterBuffer.toString());

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        HttpURLConnection conn = null;
        String res = null;

        try {
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(10 * 1000);
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));

            outputStream = conn.getOutputStream();  //发起http请求
            outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(parameterBuffer.toString()); //post data
            outputStreamWriter.flush();

            if (conn.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + conn.getResponseCode());
            }

            inputStream = conn.getInputStream();
            res = inputStream2String(inputStream);

            if (outputStreamWriter != null)
                outputStreamWriter.close();
            if (outputStream != null)
                outputStream.close();
            if (inputStream != null)
                inputStream.close();
        } catch (Exception e) {
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect(); //中断连接
            }
        }

        return res;
    }

    public static String httpGet(String urlPath) {

        String res = null;
        HttpURLConnection conn = null;
        InputStream inStream = null;
        try {

            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);

            if (conn.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + conn.getResponseCode());
            }

            inStream = conn.getInputStream(); //发起http请求
            res = inputStream2String(inStream);
            //System.out.println(res);
            if (inStream != null)
                inStream.close();

        } catch (Exception e) {
            //e.printStackTrace();
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect(); //中断连接
            }
        }
        return res;
    }

    public static String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        InputStreamReader inRead = new InputStreamReader(in, "utf-8");
        char[] b = new char[4096];

        for (int n; (n = inRead.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }

        if(inRead!=null)
            inRead.close();

        return out.toString();
    }

}
